<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { h, onMounted, onUnmounted, ref, watch } from 'vue'

import { Page } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Modal as AntModal, Button, message, Space, Spin, Tag } from 'ant-design-vue'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { allIndex, getFactoryIndex, getTreeAll } from '#/api/goods/scmGoods'
import {exportProductOrderList, getProductOrderList} from '#/api/productOrder'
import { requestClient } from '#/api/request'

async function fetchgetFactoryIndex({ keyword = '' }: Record<string, any>) {
  const { list } = await getFactoryIndex({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

const keyword4 = ref('')

const categoryOptions = ref([]) // 货品分类树
const timeCategoryOptions = ref([]) // 时间
const fetching = ref(false)

const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'goods_code',
      label: '简码',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'goods_no',
      label: '货号',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '已标记',
            value: 1,
          },
          {
            label: '未标记',
            value: 0,
          },
        ],
        showSearch: true,
      },
      fieldName: 'is_cw_sign',
      operator: '=',
      label: '标记状态',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'production_sn',
      label: '生产编号',
      operator: 'LIKE',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchgetFactoryIndex,
          mode: 'multiple',
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword4.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword4.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'followOrder*factory_id',
      operator: 'IN',

      label: '供货商',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'production_type',
      label: '类型',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '模糊搜索',
        allowClear: true,
      },
      fieldName: 'created',
      label: '制单人',
      operator: 'LIKE',
    },
    {
      component: 'RangePicker',
      componentProps: {
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },

        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD ',
      },
      fieldName: 'create_time',
      operator: 'RANGE',
      label: '下单时间',
    },
    {
      component: 'RangePicker',
      componentProps: {
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        // showTime: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'cw_sign_time',
      operator: 'RANGE',
      label: '财务标记/取消时间',
    },
    {
      component: 'RangePicker',
      componentProps: {
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },

        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'purchase_completed',
      operator: 'RANGE',
      label: '订单完结',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
    trigger: 'row',
  },
  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    {
      field: 'goods_code',
      title: '简码',
      width: 150,
    },
    { title: '货号', field: 'goods_no', width: 110, slots: { default: 'goods_no' } },
    {
      title: '标记状态',
      field: 'is_cw_sign',
      width: 80,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '完成',
            value: 1,
          },
          { color: 'error', label: '未完成', value: 0 },
        ],
      },
    },

    {
      title: '生产单号',
      field: 'production_sn',
      width: 120,
    },
    {
      title: '加工厂',
      field: 'follow_order.SupplyNa',
      width: 210,
    },
    {
      title: '采购性质',
      field: 'production_type',
      width: 100,

      slots: { default: 'production_type' },
    },
    {
      title: '交货日期',
      field: 'expected_completion_date',
      width: 100,
      sortable: true,
    },
    { title: '生产总量', field: 'plan_total_num', width: 100 },
    { title: '订单备注', field: 'order_remark', width: 100 },
    { title: '制单人', field: 'created', width: 500 },
    { title: '下单时间', field: 'create_time', width: 150 },

    { title: '财务标记/取消时间', field: 'cw_sign_time', width: 150 },
    { title: '订单完结', field: 'purchase_completed', width: 150 },

    { title: '返单次数', field: 'back_order_times', width: 70 },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await getProductOrderList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
        })
        currentFormValues.value = {
          search,
          is_excel_export:1,
          page: page.currentPage,
          limit: page.pageSize,
          params: {},
        }
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  id: 'goods_purchase',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
}

onMounted(async () => {
  const cateRes = await allIndex()
  categoryOptions.value = cateRes.list
  const timeRes = await getTreeAll()
  timeCategoryOptions.value = timeRes
})

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions })

//  按钮的禁用状态
const isDisabled = ref(true)
const isFinancialMarkDisabled = ref(true)
const isFinancialUnmarkDisabled = ref(true)

// 检查并更新拷贝按钮状态
function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      // 检查是否包含已财务标记的记录
      const hasFinancialMark = selectedRecords.some((record) => record.is_cw_sign === 1)
      const hasUnmarkedFinancial = selectedRecords.some((record) => record.is_cw_sign === 0)
      isDisabled.value = !selectedRecords || selectedRecords.length === 0
      isFinancialMarkDisabled.value = !selectedRecords || selectedRecords.length === 0 || hasFinancialMark
      isFinancialUnmarkDisabled.value = !selectedRecords || selectedRecords.length === 0 || hasUnmarkedFinancial
    } else {
      isDisabled.value = true
      isFinancialUnmarkDisabled.value = true
      isFinancialMarkDisabled.value = true
    }
  } catch {
    isDisabled.value = true
    isFinancialUnmarkDisabled.value = true
    isFinancialMarkDisabled.value = true
  }
}

// 使用watch监听gridApi的变化
watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)

function sign(type: string) {
  const textArr: any = []
  textArr.success = '标记完结'
  textArr.error = '反标记完结'
  textArr.clear_jh_code = '清空计划单'
  const text = textArr[type] || '未知'
  AntModal.confirm({
    title: '提示',
    content: `确定要${text}吗？`,
    okText: '是',
    cancelText: '否',
    onOk() {
      const data = gridApi.grid.getCheckboxRecords()
      const params = data.map((item: any) => item.id)
      requestClient.post('admin/ProductOrder/sign', { ids: params, type }, { responseReturn: 'raw' }).then((res: any) => {
        gridApi.reload()
        if (res.data.code === 1) {
          message.success(res.data.msg)
        } else {
          message.error(res.data.msg)
        }
      })
    },
    onCancel() {},
  })
}

/**
 * 导出
 */
const currentFormValues: any = ref()
function handExcel() {
  if (currentFormValues.value.search.length === 0 && currentFormValues.value.quick_search === undefined) {
    message.error({ content: '需要筛选条件' })
  } else {
    exportProductOrderList(currentFormValues.value).then((res: any) => {
      window.open(res.path)
    })
  }
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="handExcel">导出查询的全部记录</Button>
            <Button type="primary" :disabled="isFinancialMarkDisabled" @click="sign('success')">财务标记</Button>
            <Button type="primary" danger :disabled="isFinancialUnmarkDisabled" @click="sign('error')">财务反标记</Button>
          </Space>
        </div>
      </template>
      <!-- 操作列插槽 -->
      <template #goods_no="{ row }">
        <Tag color="blue">{{ row.goods_no }}</Tag>
      </template>
      <template #erp_id="{ row }">
        <Tag v-if="row.goods?.erp_id > 0" color="green">已推送</Tag>
        <Tag v-else color="red">未推送</Tag>
      </template>
      <template #posted="{ row }">
        <Tag v-if="row.goodsPurchase?.posted > 0" color="green">已审核</Tag>
        <Tag v-else color="red">未审核</Tag>
      </template>

      <template #production_type="{ row }">
        <Tag color="blue">{{ row.production_type }}</Tag>
      </template>
    </Grid>
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
